package edu.egypt.sharedpreferences;

import android.app.Activity;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class SharedPreferencesSampleActivity extends Activity implements OnClickListener {
    private Button saveButton;
	private Button loadButton;
	private Button emptyButton;
	private EditText editText;
	private SharedPreferences prefs;
	private Editor editor;
	private EditText numberText;

	//objective 2: saving text,number using SharedPreferences  
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        //create SharedPreferences object
        prefs = getSharedPreferences("text_prefs", MODE_PRIVATE);
        editor = prefs.edit();
        
        intializeUI();
    }

	private void intializeUI() {
		saveButton = (Button)findViewById(R.id.save_button);
		loadButton = (Button)findViewById(R.id.load_button);
		emptyButton = (Button)findViewById(R.id.empty_button);
		editText = (EditText)findViewById(R.id.editText1);
		numberText = (EditText)findViewById(R.id.editText2);
		
		saveButton.setOnClickListener(this);
		loadButton.setOnClickListener(this);
		emptyButton.setOnClickListener(this);
		
		
	}

	@Override
	public void onClick(View v) {
		if(v.equals(saveButton)){
			editor.putString("text_value", editText.getText().toString());
			editor.putFloat("number_value", Float.parseFloat(numberText.getText().toString()));
			editor.commit();
		}else if(v.equals(loadButton)){
			String savedText =  prefs.getString("text_value", "");
			float savedNumber = prefs.getFloat("number_value", 0);
			
			editText.setText(savedText);
			numberText.setText(savedNumber+"");
		}else{
			editText.setText("");
		}
		
	}
}